package com.invengo.testrfid.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;

import com.invengo.testrfid.app.dao.QueryManager;
import com.invengo.testrfid.app.dao.RfidCageBind;
import com.invengo.testrfid.app.entity.MessageEntity;
import com.invengo.testrfid.app.proxy.ProxyNetWorker;
import com.invengo.testrfid.app.utils.Constant;
import com.invengo.testrfid.app.utils.ExportExcelData;
import com.invengo.testrfid.app.utils.GsonUtils;
import com.invengo.testrfid.app.utils.MyDialogueUtils;
import com.invengo.testrfid.app.utils.MyDialogueUtilsListenser;
import com.invengo.testrfid.app.utils.SoundPlayUtils;
import com.invengo.testrfid.mvp.contract.UploadDetailContract;
import com.invengo.testrfid.mvp.ui.adapter.MyDefaultAdapter;
import com.invengo.testrfid.mvp.ui.adapter.UploadDetailAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import jxl.write.WriteException;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;


@ActivityScope
public class UploadDetailPresenter extends BasePresenter<UploadDetailContract.Model, UploadDetailContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private QueryManager queryManager;

    private UploadDetailAdapter mAdapter;

    private List<RfidCageBind> mData = new ArrayList();

    private Context context;

    @Inject
    public UploadDetailPresenter(UploadDetailContract.Model model, UploadDetailContract.View rootView) {
        super(model, rootView);
        this.queryManager = QueryManager.getManager();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.queryManager = null;
    }

    public void initView(Context context) {

        this.context = context;
        if (mAdapter == null) {
            mAdapter = new UploadDetailAdapter(mData);
            mRootView.setAdapter(mAdapter);//设置Adapter
            handItemClick();
        }
        mData.clear();

        //        // 加载本地的文件
        Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {

                mData.addAll(queryManager.getRfidCageQuery().loadAllData());
                emitter.onNext("-data-");

            }
        });
        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String data) throws Exception {
                mAdapter.notifyDataSetChanged();
            }
        };
        observable.subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(consumer);

    }


    /**
     * 处理条目点击事件
     */
    private void handItemClick() {

        mAdapter.setOnItemClickListener(new MyDefaultAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {

                showDis(position);
            }
        });
    }

    private void showDis(final int position) {

        MyDialogueUtils dia = new MyDialogueUtils(context);
        dia.setTitle("提示");
        dia.setBody("是否删除该条数据？");
        dia.setFoot("取消", "删除");
        dia.registerListenser(new MyDialogueUtilsListenser() {

            @Override
            public void onPositiveClick(String text) {

                RfidCageBind rfidCageBind = mData.get(position);
                queryManager.getRfidCageQuery().delete(rfidCageBind);
                mData.remove(position);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onNegetiveClick(String text) {

            }
        });
        dia.showDia();

    }


    public void showSearchDia() {

        MyDialogueUtils dia = new MyDialogueUtils(context, MyDialogueUtils.DialogueType.EDIT);
        dia.setTitle("提示");
        dia.setBody(100);
        dia.setFoot("取消", "确定");
        dia.registerListenser(new MyDialogueUtilsListenser() {

            @Override
            public void onPositiveClick(String text) {

                queryData(text);
            }

            @Override
            public void onNegetiveClick(String text) {

            }
        });
        dia.showDia();
    }

    private void queryData(String data) {

        List<RfidCageBind> rfidCageBinds = new ArrayList<>();
        if (data.trim().length() < 1) {
            rfidCageBinds = queryManager.getRfidCageQuery().loadAllData();
        } else {
            rfidCageBinds = queryManager.getRfidCageQuery().queryDataByCageByCondition(data);
        }
        mData.clear();
        mData.addAll(rfidCageBinds);
        mAdapter.notifyDataSetChanged();
    }


    public void exportData() {


        Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> es) throws Exception {


                try {

                    List<RfidCageBind> rfidCageBinds = queryManager.getRfidCageQuery().loadAllData();
                    new ExportExcelData().exportExcelData(rfidCageBinds);
                } catch (IOException e) {

                    e.printStackTrace();
                    es.onNext("文件读取错误");
                } catch (WriteException e) {

                    e.printStackTrace();
                    es.onNext("文件写入错误");
                }

                es.onNext("数据导出成功");
            }
        }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread());

        observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(@NonNull String s) throws Exception {

                mRootView.showMessage(s);
            }
        });


    }
}
